package com.baox.agridata.synchronous.schedule;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baox.agridata.synchronous.constant.*;
import com.baox.agridata.synchronous.entity.*;
import com.baox.agridata.synchronous.result.HttpResultResponse;
import com.baox.agridata.synchronous.result.Result;
import com.baox.agridata.synchronous.service.*;
import com.baox.agridata.synchronous.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 检疫证(成都检疫证的落地反馈)
 */

@Slf4j
@Component
public class SiChuanToChengDuLandingFeedbackSchedule {


    @Value("${TOCD.LandingAnimalB}")
    private String LandingAnimalBTime;

    @Value("${TOCD.LandingAnimalA}")
    private String LandingAnimalATime;

    @Autowired
    private TCCABService tccabService;

    @Autowired
    private TCCAAService tccaaService;

    @Autowired
    private AsyncLogOperationService asyncLogOperationService;

    @Autowired
    private ScAgricultureTaskService scAgricultureTaskService;


    /**
     * 成都的动物B在四川落地的数据，状态同步给成都
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0 * * * ?")
    public void synchronizationTCCABLandingToChengdu() {
        ScAgricultureTask sxAgricultureTask = scAgricultureTaskService.selectTaskStatus(TaskNameConstant.T_CC_AB_LANDING);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【成都动物B在四川落地】，数据状态同步给成都任务开始");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "LandingAnimalB";
                String l_filePath_record = l_file.getPath() + File.separator + "Record" + File.separator + "LandingAnimalB";
                String nowTime = DateUtil.jianOneMinutes() + ":00";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, DataConstant.FILE_NAME)) {
                    LandingAnimalBTime = l_file.readLastLineV2(l_filePath, DataConstant.FILE_NAME);
                    if (StringUtils.isEmpty(LandingAnimalBTime) || "null".equals(LandingAnimalBTime)) {
                        LandingAnimalBTime = DateUtil.jianFiveMinutes(nowTime);
                    }
                }
                List<TCCABEntity> l_list = tccabService.selectAnimalBLandingFeedback(LandingAnimalBTime, nowTime);
                if (l_list != null && l_list.stream().count() > 0) {
                    Integer resultCode = sendNetWorkData(l_list, HttpRequestUrl.LANDING_ANIMAL_B);
                    if (resultCode.intValue() == Result.ok().getCode()) {  //当发送成功后，继续后续的操作
                        boolean timeCreateStatus = l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                        log.info("【成都动物B在四川落地】文件记录生成状态：{},文件读取内容为：{},记录内容为：{},发送成都的条目数为：{}", timeCreateStatus, LandingAnimalBTime, nowTime, l_list.size());

                        //---------------异步记录检疫证号-----------
                        List<String> factoryCodeList = l_list.stream().map(TCCABEntity::getFactoryCode).collect(Collectors.toList()); //检疫证号记录数据
                        asyncLogOperationService.insertFactoryCodeRecord(factoryCodeList, LandingAnimalBTime, nowTime, l_filePath_record);  //异步记录检疫证号
                    } else {
                        log.info("【成都动物B在四川落地】network error，时间节点为：{}---{}", LandingAnimalBTime, nowTime);
                    }
                } else {
                    log.info("【成都动物B在四川落地】本次未查询到数据，时间节点为：{}---{}", LandingAnimalBTime, nowTime);
                    l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);  //发送成功后，将新的时间重新写入文件中，下次读取
                }
            } catch (Exception e) {
                log.info("【成都动物B在四川落地】出现了错误：" + e.getMessage());
            }
        } else {
            log.info("【成都动物B在四川落地】同步任务未开启");
        }
    }


    /**
     * 成都的动物A发送到四川，外省落地的数据，状态同步给成都
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0 * * * ?")
    public void synchronizationTCCAALandingToChengdu() {
        ScAgricultureTask sxAgricultureTask = scAgricultureTaskService.selectTaskStatus(TaskNameConstant.T_CC_AA_LANDING);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【成都动物A发送到四川,在外省落地A证状态回传给成都】，数据状态同步给成都任务开始");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "LandingAnimalA";
                String l_filePath_record = l_file.getPath() + File.separator + "Record" + File.separator + "LandingAnimalA";
                String nowTime = DateUtil.jianOneMinutes() + ":00";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, DataConstant.FILE_NAME)) {
                    LandingAnimalATime = l_file.readLastLineV2(l_filePath, DataConstant.FILE_NAME);
                    if (StringUtils.isEmpty(LandingAnimalATime) || "null".equals(LandingAnimalATime)) {
                        LandingAnimalATime = DateUtil.jianFiveMinutes(nowTime);
                    }
                }
                List<TCCAAEntity> l_list = tccaaService.selectChengDuAnimalALandingBack(LandingAnimalATime, nowTime);
                if (l_list != null && l_list.stream().count() > 0) {
                    Integer resultCode = sendNetWorkData(l_list, HttpRequestUrl.LANDING_ANIMAL_A);
                    if (resultCode.intValue() == Result.ok().getCode()) {  //当发送成功后，继续后续的操作
                        boolean timeCreateStatus = l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                        log.info("【成都动物A发送到四川,在外省落地A证状态回传给成都】文件记录生成状态：{},文件读取内容为：{},记录内容为：{},发送成都的条目数为：{}", timeCreateStatus, LandingAnimalATime, nowTime, l_list.size());

                        //---------------异步记录检疫证号-----------
                        List<String> factoryCodeList = l_list.stream().map(TCCAAEntity::getFactoryCode).collect(Collectors.toList()); //检疫证号记录数据
                        asyncLogOperationService.insertFactoryCodeRecord(factoryCodeList, LandingAnimalATime, nowTime, l_filePath_record);  //异步记录检疫证号
                    } else {
                        log.info("【成都动物A发送到四川,在外省落地A证状态回传给成都】network error，时间节点为：{}---{}", LandingAnimalATime, nowTime);
                    }
                } else {
                    log.info("【成都动物A发送到四川,在外省落地A证状态回传给成都】本次未查询到数据，时间节点为：{}---{}", LandingAnimalATime, nowTime);
                    l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);  //发送成功后，将新的时间重新写入文件中，下次读取
                }
            } catch (Exception e) {
                log.info("【成都动物A发送到四川,在外省落地A证状态回传给成都】出现了错误：" + e.getMessage());
            }
        } else {
            log.info("【成都动物A发送到四川,在外省落地A证状态回传给成都】同步任务未开启");
        }
    }

    /**
     * 匹配网络请求
     *
     * @param obj
     * @param requestUrl
     * @return
     */
    private Integer sendNetWorkData(List<?> obj, String requestUrl) {
        Integer resultCode = 0;
        try {
            String jsonData = JSON.toJSONString(obj);
            byte[] gzipData = GZIPUtils.compress(jsonData); //开始压缩
            HttpResultResponse result = HttpUtils.post(requestUrl, gzipData, HttpUtils.headers);  //发送网络请求
            JSONObject jsonObject = JSON.parseObject(result.getBody());
            resultCode = jsonObject.getInteger("code");
        } catch (Exception e) {
            e.printStackTrace();
            return resultCode;
        }
        return resultCode;
    }


}
